<template>
  <div class="wrap">
    <div class="title">
      <img src="../../images/main/server.png" alt>
      <span class="back" @click="backServer()">服务商管理</span>
      <img class="right" src="../../images/main/right.png" alt>
      <span>{{$route.query.id ? '修改服务商' : '新增服务商'}}</span>
    </div>
    <div class="clear"></div>
    <div class="body">
      <div class="body-box">
        <div class="list firlist">
          <span class="txt"><img class="red" src="../../images/main/red.png" alt>
          服务商名称：</span>
          <input type="text" ref="serviceName" maxlength="30" @blur="serviceNameBlur" v-model="param.serviceName" class="input" placeholder="请输入服务商名称">
        <div v-if="check.name && !param.serviceName" style="color:red;padding-left:200px;padding-top:10px;">请先输入服务商名称</div>
        </div>
        
        <div class="list">
          <span class="txt"><img class="red" src="../../images/main/red.png" alt>
          服务商账号：</span>
          <input v-if="$route.query.id" readonly type="text" ref="serviceAccount" @blur="serviceAccountBlur" @input="serviceAccountInput" maxlength="20" v-model="param.serviceAccount" class="input" placeholder="请输入服务商账号">
          <input v-else type="text" ref="serviceAccount" @blur="serviceAccountBlur" @input="serviceAccountInput" maxlength="20" v-model="param.serviceAccount" class="input" placeholder="请输入服务商账号">
          <span class="tips">合伙人账号初始密码为：yunlehui2019</span>
          <div v-if="check.account && !param.serviceAccount" style="color:red;padding-left:200px;padding-top:10px;">请先输入服务商账号</div>
        </div>
        <div class="list ">
          <span class="txt"><img class="red" src="../../images/main/red.png" alt>
          服务商联系人：</span>
          <input type="text" ref="serviceName" maxlength="30" @blur="serviceContactsBlur" v-model="param.serviceContacts" class="input" placeholder="请输入服务商联系人">
        <div v-if="check.contacts && !param.serviceContacts" style="color:red;padding-left:200px;padding-top:10px;">请先输入服务商联系人</div>
        </div>
        <div class="list">
          <span class="txt"><img class="red" src="../../images/main/red.png" alt>
          手机号</span>
          <input type="text" maxlength="11" ref="servicePhone" v-model="param.servicePhone" class="input" placeholder="请输入手机号" @input="setPhone" @blur="servicePhoneBlur">
          <div v-if="check.phone && !param.servicePhone" style="color:red;padding-left:200px;padding-top:10px;">请先输入手机号</div>
          <div v-else-if="check.phone && param.servicePhone.length != 11" style="color:red;padding-left:200px;padding-top:10px;">请先输入正确的手机号</div>
        </div>

        <!-- <div class="upload">
          <div class="uptitle">上传头像或logo：</div>
          <div class="upimg">
            <img :src="param.serviceLogo" alt>
            <div class="info">
              <div class="uptxt firtxt">温馨提示：</div>
              <div class="uptxt">建议上传尺寸为960*675，大小不超过4M,jpg或png格式。</div>
              <el-upload
                class="upload-demo"
                :action="$store.state.url+ '/tPartner/upload'"
                :on-success="uploadsu">
                <el-button size="small" type="primary" class="btn">点击上传</el-button>
              </el-upload>
            </div>
          </div>
        </div> -->
      <div class="upload">
        <div class="uptitle">上传头像或logo：</div>
        <div class="upimg" style="overflow: hidden;">
          <div style="overflow: hidden;text-align: center;margin-left: 144px; float: left;width:320px;">
            <img
              style="width: 320px;height: 200px;"
              ref="preview"
              :src="param.serviceLogo ? param.serviceLogo : require('../../images/main/upimg.png')"
            />
          </div>
          <div class="info">
            <div class="uptxt firtxt">温馨提示：</div>
            <div class="uptxt">建议上传尺寸为960*675，大小不超过8M,jpg或png格式。</div>
            <el-upload
              class="upload-demo"
              accept=".jpg,.jpeg,.png,.gif"
              :before-upload="elUploadBefore"
              :action="$store.state.url+ '/tPartner/upload'"
              :on-success="uploadsu">
              <el-button size="small" type="primary" class="btn">{{ param.serviceLogo ? '重新上传' : '点击上传' }}</el-button>
            </el-upload>
            <div v-if=" param.serviceLogo == require('../../images/main/upimg.png')" style="color:red;padding-top:10px;">请先上传头像或logo</div>
          </div>

        </div>

      </div>
        <div class="clear"></div>
        <div class="list">
          <span class="txt">
            <img class="red" src="../../images/main/red.png"/>
            服务区域：
          </span>
          <span style="padding-left:40px;">
            <el-checkbox
              v-for="(item) in  areaList"
              :key="item.id"
              :value="item.id"
              @change="areaBlur"
              v-model="item.selected"
              >
              {{ item.regionName }}
            </el-checkbox>
            </span>
           <div v-if="check.area && !param.regionId" style="color:red;padding-left:200px;padding-top:10px;">请先选择服务区域</div>
          <!-- <span class="radio">
            <span v-for="(item,index) in areaList" :key="index">
              <input
                type="radio"
                  :id="'area_'+item.id" v-model="param.regionId" :checked="(param.regionId==item.id)" :value="item.id"  name="area" />
              <label :for="'area_'+item.id">{{item.regionName}}</label>
            </span>
          </span> -->
        </div>
        <div class="list">
          <span class="txt"><img class="red" src="../../images/main/red.png" alt>
          服务类别：</span>
          <input type="text" ref="serviceType" @blur="typeBlur" v-model="param.serviceType" class="input" maxlength="20" placeholder="请输入服务类别"/>
          <div v-if="check.type && !param.serviceType" style="color:red;padding-left:200px;padding-top:10px;">请先输入服务类别</div>
        </div>
        <div class="list lastlist">
          <span class="txt" style="float:left;"><img class="red" src="../../images/main/red.png" alt>
          服务商介绍：</span>
          <textarea name="" @blur="introBlur" ref="serviceIntroduce" v-model="param.serviceIntroduce" id="" cols="30" rows="10">

          </textarea>
          <div v-if="check.intro && !param.serviceIntroduce" style="color:red;padding-left:200px;padding-top:10px;">请先输入服务商介绍</div>
        </div>
        <!-- <div class="submit" @click="submit">提交</div> -->
        <div class="button">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submit">提交</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import axios from 'axios'
import qs from 'qs'
export default {
  created () {
    // this.getArea();

    
  },
  data () {
    return {
      check: {
        name: false,
        account: false,
        phone: false,
        area: false,
        type: false,
        intro: false,
        contacts: false
      },
      areaList: [],
      param: {
        regionId: '',
        serviceLogo: '',
        serviceName: '',
        serviceAccount: '',
        servicePhone: '',
        serviceType: '',
        serviceIntroduce: '',
        serviceContacts: ''
      },
    }
  },
  mounted () {
    this.getArea();
    if( this.$route.name == 'editServer' ) {
      this.getParManDetails()
      this.title = '修改服务商'
      this.isEdit = true
      
      // this.areaList()
    }
  },
  methods: {
    getParManDetails: function () {
      if ( this.$route.name === 'editServer' ) {
      axios.post (
        `${this.$store.state.url}/tService/selectServiceDateils`,
        qs.stringify({
          id: this.$route.query.id
        })
      ).then ( response => {
        let res = response.data;
        if ( res.code == 0 ) {
          // this.param.regionId = res.data.area.split ( ',' );
          console.log ( this.areaList );
          let area = res.data.area.split ( ',' );
          for ( let i = 0, len = this.areaList.length; i < len; i ++ ) {
            let item = this.areaList[i];
            console.log(item)
            for ( let j = 0; j < area.length; j ++ ) {
              if ( item.regionName == area[j] ) {
                item.selected = true;
              }
            }
          }


          this.param.serviceLogo = res.data.serviceLogo;
          this.param.serviceName = res.data.serviceName;
          this.param.serviceAccount = res.data.serviceAccount;
          this.param.servicePhone = res.data.servicePhone;
          this.param.serviceType = res.data.serviceType;
          this.param.serviceIntroduce = res.data.serviceIntroduce;
          this.param.serviceContacts = res.data.serviceContacts;
        }
      });
    }
    },
    serviceAccountInput(){
      this.param.serviceAccount = this.param.serviceAccount.replace ( /[^a-zA-Z0-9]/img, '' );
    },
    cancel(){
      this.$router.back(-1);
    },
    typeBlur() {
      this.check.type = true;
      if ( !this.param.serviceType ) {
        // this.$refs.serviceType.focus ();
      }
    },
    areaBlur() {
      this.check.area = true;
    },
    introBlur() {
      this.check.intro = true;
      if ( !this.param.serviceIntroduce ) {
        // this.$refs.serviceIntroduce.focus ();
      }
    },
    serviceNameBlur() {
      this.check.name = true;
      if ( !this.param.serviceName ) {
        // this.$refs.serviceName.focus ();
      }
    },
    serviceAccountBlur() {
      this.check.account = true;
      if ( !this.param.serviceAccount ) {
        // this.$refs.serviceAccount.focus ();
      }
    },
serviceContactsBlur() {
      this.check.contacts = true;
      if ( !this.param.serviceAccount ) {
        // this.$refs.serviceAccount.focus ();
      }
    },
    
    servicePhoneBlur() {
      this.check.phone = true;
      if ( !this.param.servicePhone || this.param.servicePhone.length != 11 ) {
        // this.$refs.servicePhone.focus ();
      }
    },
    /*
    * 设置手机号
     */
     setPhone: function () {
       this.param.servicePhone =  this.param.servicePhone.replace(/[^0-9]/ig,"");
     },
	  /**
	   * 设置期限
	   */
	  setAge: function () {

		  this.param.joinAge = Math.round(this.param.joinAge.replace(/\./g,''))
		  if(this.param.joinAge < 1) {
			  this.param.joinAge = 0
		  }
	  },
    // 限制上传
    elUploadBefore(file) {
      console.log(file.type.search("image/"));
      const isImg = file.type.search("image/") == -1;
      const isLt8M = file.size / 1024 / 1024 < 8;

      if (isImg) {
        this.$message.error("请上传图片类型!");
      }
      if (!isLt8M) {
        this.$message.error("图片大小不能超过 8MB!");
      }
      return !isImg && isLt8M;
    },
    backServer: function () {
      this.$router.push({
        path:'/main/server'
      })
    },
    uploadsu( response, file, item ) {
      let f;
      if (window.createObjectURL!=undefined) {
        f = window.createObjectURL(file.raw) ;
      } else if (window.URL!=undefined) { // mozilla(firefox)
        f = window.URL.createObjectURL(file.raw) ;
      } else if (window.webkitURL!=undefined) { // webkit or chrome
        f = window.webkitURL.createObjectURL(file.raw) ;
      }
      let img = new Image ();
      let el_img = this.$refs.preview;
      img.src = f;
      img.onload = () => {
        let w = img.width;
        let h = img.height;
        let vesW = 320, vesH = 200;
        let sureW, sureH;
        if ( h * vesW / w >= vesH ) {
          sureH = vesH;
          sureW = vesH / h * w;
        } else {
          sureW = vesW;
          sureH = 328 / w * h;
        }
        el_img.style.width = sureW + 'px';
        el_img.style.height = sureH + 'px';
      };

      if ( response.code == 0 ) {
        this.param.serviceLogo = response.data.src;
      }
      this.$alert ( '上传成功' );
    },
    getArea: function () {
      let that = this
      axios({
        method:'post',
        async: false,
        url:`${that.$store.state.baseUrl}/backstage/api/tRegion/selectAll`,
      }).then(response => {
        let res = response.data;
        if (res.code == 0) {
        // that.areaList = res.data.data
          if ( res.data ) {
            res.data.forEach ( item => {
              item.selected = false;
              that.areaList.push ( item );
            });
          }
        }
      })
    },
    submit() {
      let _this = this;
      var that = this
      if ( !this.param.serviceName ) {
        this.serviceNameBlur();
        this.$refs.serviceName.focus ();
        // this.$alert ( '请填写服务商名称' );
        return;
      } else if ( !this.param.serviceAccount ) {
        this.serviceAccountBlur();
        this.$refs.serviceAccount.focus ();
        // this.$alert ( '请填写服务商账号' );
        return;
      } else if ( !this.param.servicePhone ) {
        this.servicePhoneBlur();
        this.$refs.servicePhone.focus ();
        // this.$alert ( '请填写服务商手机号' );
        return;
      } else if ( this.param.servicePhone.length != 11 ) {
        this.servicePhoneBlur();
        this.$refs.servicePhone.focus ();
        // this.$alert ( '服务商手机号格式不正确' );
        return;
      }else if ( !this.param.regionId ) {
        this.areaBlur();
        return;
      } else if ( !this.param.serviceType ) {
        this.typeBlur();
        this.$refs.serviceType.focus ();
        // this.$alert ( '请填写服务商类型' );
        return;
      } else if ( !this.param.serviceIntroduce ) {
        this.introBlur()
        this.$refs.serviceIntroduce.focus ();
        // this.$alert ( '请填写服务商介绍' );
        return;
      }
      this.param.id = this.$route.query.id
      let url = '';
      if ( this.$route.name == 'editServer' ) {
        url = `${this.$store.state.url}/tService/updateService`;
      } else {
        url = `${this.$store.state.url}/tService/addService`;
      }
      // if(this.param.serviceLogo.search('base64,')){
      //   this.param.serviceLogo = ''
      // }
      axios({
        method: 'post',
        url: url,
        data: this.param
      }).then ( response => {
        let res = response.data;
        if ( res.code == 0 ) {
          this.$store.state.fn.success( this.$route.name == 'editServer' ? '修改成功' : '新增成功' ).then (() => {
            _this.$router.back ( -1 );
          });
          let logData = {
                loginTime:this.$cookie.get("loginTime"),
                account:this.$cookie.get("userAccount"),
                content:this.isEdit?'修改服务商':'增加服务商',
              operationTime:this.setDate(new Date()) + ' ' +this.setTime(new Date())
              }
              axios({
          method: "post",
          url: `${that.$store.state.url}/log/addLog`,
          data: qs.stringify(logData)
        }).then( (res) => {
          console.log(res,'222')
        })
        } else {
          this.$alert (res.msg );
        }
      }, () => {
        this.$alert ( this.$route.name == 'editServer' ? '系统错误' : '系统错误' );
      });
    },
     /**
     * 根据时间毫秒数 返回年月日
     */
    setDate: function(str) {
      let times = new Date(str);
      return `${times.getFullYear()}-${
        times.getMonth() + 1 < 10
          ? "0" + (times.getMonth() + 1)
          : times.getMonth() + 1
      }-${times.getDate() < 10 ? "0" + times.getDate() : times.getDate()}`;
    },
    /**
     * 根据时间毫秒数 返回时分秒
     */
    setTime: function(str) {
      let times = new Date(str);
      return `${
        times.getHours() < 10 ? "0" + times.getHours() : times.getHours()
      }:${
        times.getMinutes() < 10 ? "0" + times.getMinutes() : times.getMinutes()
      }:${
        times.getSeconds() < 10 ? "0" + times.getSeconds() : times.getSeconds()
      }`;
    }
  },
  watch: {
    areaList: {
      deep: true,
      handler ( val ) {
        this.param.regionId = '';
        for ( let i = 0, len = val.length; i < len; i ++ ) {
          if ( val[i].selected ) {
            this.param.regionId += val[i].id;
            if ( i < val.length - 1 ) {
              this.param.regionId += ',';
            }
          }
        }
      }
    }
  }
};
</script>
<style type="text/scss" lang="scss" scoped >
/deep/ .el-upload-list {
  display: none;
}
.back {
  cursor: pointer;
}
.wrap {
  /* padding: 68px 136px;
  width: 100%; */
  width: 90%;
  margin: 40px auto;
}
.title {
  height: 33px;
  line-height: 33px;
  font-size: 24px;
  font-family: PingFangSC-Medium;
  font-weight: bold;
}
.title span {
  float: left;
}
.title img {
  width: 28px;
  height: 26px;
  float: left;
  padding-top: 5px;
  margin-right: 10px;
}
.title .right {
  width: 11px;
  height: 18px;
  padding-top: 9px;
  margin-left: 5px;
  margin-right: 6px;
}
.body {
  background: #ffffff;
  box-shadow: 0 5px 20px 0 rgba(0, 0, 0, 0.05);
  border-radius: 6px;
  /* width: 1490px; */
  /* height:1430px; */
  /* margin-top: 70px; */
  /* margin-left: 48px; */
  /* padding-left: 233px; */
  /* padding-top: 90px; */
  box-sizing: border-box;
}

.list {
  height: 40px;
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #000000;
  line-height: 40px;
  margin-top: 49px;
}
.firlist {
  margin-top: 0;
}
.lastlist {
  height: 182px;
}
.red {
  width: 10px;
  height: 10px;
}
.txt {
  width: 145px;
  display: inline-block;
  text-align: left;
  font-family: PingFangSC-Medium;
  font-size: 18px;
  font-weight: bold;
  color: #000000;
}
.input {
  background: #ffffff;
  box-shadow: inset 0 1px 3px 0 rgba(0, 0, 0, 0.5);
  width: 502px;
  height: 40px;
  margin-left: 50px;
  padding-left: 10px;
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #888888;
  box-sizing: border-box;
  text-align: center;
}
.tips {
  font-family: PingFangSC-Regular;
  font-size: 14px;
  color: #727272;
  margin-left: 35px;
}
.upload{
  clear: both;
  overflow: hidden;
}
.uptitle {
  height: 25px;
  line-height: 25px;
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #000000;
  font-weight: bold;
  float: left;
  margin-top: 40px;
}
.upimg {
  margin-top: 40px;
  margin-left: 50px;
  float: left;
}
.upimg img {
  width: 205px;
  height: 205px;
  float: left;
  /* margin-left: 195px; */
}
.info {
  width: 472px;
    padding-top: 28px;
    float: left;
    margin-left: 7px;
}
.uptxt {
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #888888;
  height: 30px;
  line-height: 30px;
  margin-top: 15px;
}
.firtxt {
  margin-top: 0;
}
.btn {
  background: #085dab;
  width: 255px;
  height: 55px;
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #ffffff;
  letter-spacing: 0.03px;
  text-align: center;
  line-height: 55px !important;
  margin-top: 20px;
  cursor: pointer;
  padding: 0px;
}
.clear {
  clear: both;
}
.radio {
  display: inline-block;
  padding-left: 25px;
}
.radio img {
  width: 25px;
  height: 25px;
  float: left;
  border-radius: 50%;
  margin-left: 25px;
}
.radio span {
  width: 80px;
  height: 25px;
  line-height: 25px;
  margin-left: 17px;
  float: left;
  margin-right: 10px;
  font-weight: bold;
}
.date {
  width: 172px;
  border-right: 0px;
}
.year {
  background: #085dab;
  border: 1px solid #979797;
  width: 45px;
  height: 38px;
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #ffffff;
  line-height: 38px;
  text-align: center;
  display: inline-block;
  font-weight: bold;
}
textarea {
  width: 502px;
  height: 182px;
  margin-left: 50px;
  resize: none;
}
.submit {
  cursor: pointer;
  background: #085dab;
  width: 255px;
  height: 55px;
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #ffffff;
  line-height: 55px;
  text-align: center;
  /* margin-top: 60px; */
  /* margin-left: 374px; */
  margin: 60px auto;
}
input[type="radio"] + label::before {
    content: "\a0"; /*不换行空格*/
    display: inline-block;
    vertical-align: middle;
    /* font-size: 18px; */
    width: 8px;
    height: 8px;
    margin-right: .4em;
    border-radius: 50%;
    border: 1px solid #085dab;
    line-height: 1;
    box-shadow:0px 0px 2px 0 rgba(0,0,0,0.50);
    border: 8px solid #fff;
}
input[type="radio"]:checked + label::before {
    background-color: #fff;
    background-clip: content-box;
    border: 8px solid #085dab;

}
input[type="radio"] {
    position: absolute;
    clip: rect(0, 0, 0, 0);
    margin-left: 58px;
}
.radio > div {
  float: left;
  padding-left: 20px;
}
.radio label {
  margin-left: 58px;
}
.radio label:first-of-type {
  margin-left: 0px;
}

.list .txt,.list .radio{
  vertical-align: middle;
}

.radio span{
  width: 80px;
  font-weight: 200;
}

.body-box{
  width: 90%;
  margin: 40px auto;
  padding: 40px 0;
}
.button {
  text-align: center;
  padding: 50px 0;
}
/deep/ .el-button{
  border-radius: 0;
}
/deep/ .el-button--primary{
  background-color: #085dab
}
@media (min-width: 1380px) {
  .body-box{
   width: 80%;
  }
}
@media (min-width: 1820px) {
  .body-box{
   width: 70%;
  }
}
@media (min-width: 1900px) {
  .body-box{
   width: 60%;
  }
}

</style>
